package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webscoket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCarMapper shoppingCarMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 下单业务
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result<OrderSubmitVO> submitOrder(OrdersSubmitDTO dto) {
        //1.判断收件地址是否为空
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if(addressBook==null){
            return Result.error(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //2.判断购物车是否为空
        List<ShoppingCart> cartList = shoppingCarMapper.list(BaseContext.getCurrentId());
        if(cartList==null || cartList.size()==0){
            return Result.error(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //3.插入订单数据表一条
        Orders orders=new Orders();
        BeanUtils.copyProperties(dto,orders);
        //订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //订单状态,未支付
        orders.setStatus(Orders.PENDING_PAYMENT);
        //支付状态,未支付
        orders.setPayStatus(Orders.UN_PAID);
        //下单用户id
        orders.setUserId(BaseContext.getCurrentId());
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //手机号，地址，收货人
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());

        orderMapper.addOrder(orders);

        //4.插入订单详情表 一条或者多条
        List<OrderDetail> orderDetailList=new ArrayList<>();
        cartList.forEach(shoppingCart -> {
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
        orderDetailMapper.addOrderDetail(orderDetailList);

        //5.清空购物车数据
        shoppingCarMapper.clean(BaseContext.getCurrentId());
        //6.返回数据
        OrderSubmitVO vo = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                            .build();
        return Result.success(vo);
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);


        //推送消息给前端实现来单提醒
        Map map=new HashMap();
        map.put("type",1);//类型
        map.put("orderId",ordersDB.getId());//订单id
        map.put("content","订单号：" + outTradeNo);
        String message= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(message);

    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 客户催单功能
     *
     * @param id
     * @return
     */
    @Override
    public Result reminder(Long id) {
        //1.非空判断
        if(id==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.根据当前id查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if(orders==null){
            return Result.error(MessageConstant.ORDER_NOT_FOUND);
        }

        //3.推送消息给商家端的浏览器
        Map map=new HashMap();
        map.put("type",2);//类型
        map.put("orderId",id);//订单id
        map.put("content","订单号：" + orders.getNumber());
        String message= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(message);
        //4.返回数据
        return Result.success();
    }
}
